import React, { useMemo, useState } from 'react';
import { Descriptions, Tag, Button, Input, InputNumber, DatePicker, Select, Form, TreeSelect } from 'antd';
import { CalendarOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

const { Option } = Select;

const SupplierTreeData = [
    {
        title: '供应商',
        key: 1,
        value: 1,
        children: [
            { title: '钢筋供应商', key: 2, value: 2 },
            {
                title: '水泥供应商',
                key: 3,
                value: 3,
                children: [
                    { title: '建筑水泥供应商', key: 6, value: 6 },
                    { title: '家用水泥供应商', key: 7, value: 7 },
                ],
            },
        ],
    },
    {
        title: '五金材料供应商',
        key: 8,
        value: 8,
        children: [
            { title: '螺丝供应商', key: 9, value: 9 },
            { title: '螺帽供应商', key: 10, value: 10 },
        ],
    }
];

const mockPurchaseList = [
    {
        subtotal: 141950.00,
        numbering: 'PO2023001',
        supplier: 1,
        name: '商品混凝土',
        specification: 'C30',
        quantity: 300,
        unit: '立方米',
        unitPrice: 450,
        rate: 0.05,
        other_fee: 200,
        remark: '快递费200',
        status: 1,
        purchaseTime: '2023-03-10',
        paymentTime: '2023-03-11',
    }
];

const mockSupplier = [
    { id: 1, name: '供应商A', type: 2 },
    { id: 2, name: '供应商B', type: 3 },
    { id: 3, name: '供应商C', type: 9 },
];

const statusMean = {
    1: '审核中',
    2: '未付款',
    3: '已取消',
    4: '已完成',
    5: '已付款'
};

const PurchaseRequestPage = () => {
    const [form] = Form.useForm();
    const [purchaseData, setPurchaseData] = useState(mockPurchaseList[0]);
    const [isEditing, setIsEditing] = useState(false);

    const statusColor = {
        1: 'processing',
        2: 'warning',
        3: 'error',
        4: 'success',
        5: 'success'
    };

    const formatCurrency = (amount) => {
        return `¥${amount?.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
    };

    const generateSupplierTreeWithSuppliers = (nodes) => {
        return nodes.map(node => {
            const childrenFromCategories = node.children ? generateSupplierTreeWithSuppliers(node.children) : [];
            const suppliersUnder = mockSupplier
                .filter(s => s.type === node.key)
                .map(s => ({
                    title: s.name,
                    key: `supplier-${s.id}`,
                    value: `supplier-${s.id}`,
                    isLeaf: true
                }));
            return {
                ...node,
                key: node.key,
                value: node.key,
                children: [...childrenFromCategories, ...suppliersUnder]
            };
        });
    };
    const supplierTreeWithSuppliers = useMemo(() => generateSupplierTreeWithSuppliers(SupplierTreeData), []);

    const findSupplierName = (id) => {
        const supplier = mockSupplier.find(s => s.id === id);
        return supplier ? supplier.name : id;
    };

    const handleEdit = () => {
        setIsEditing(true);
        form.setFieldsValue({
            ...purchaseData,
            supplier: purchaseData.supplier ? `supplier-${purchaseData.supplier}` : null,
            purchaseTime: dayjs(purchaseData.purchaseTime),
            paymentTime: dayjs(purchaseData.paymentTime)
        });
    };

    const handleCancel = () => {
        setIsEditing(false);
    };

    const handleSave = () => {
        form.validateFields().then((values) => {
            const updated = {
                ...purchaseData,
                ...values,
                supplier: String(values.supplier).startsWith('supplier-')
                    ? parseInt(String(values.supplier).replace('supplier-', ''), 10)
                    : values.supplier,
                purchaseTime: values.purchaseTime.format('YYYY-MM-DD'),
                paymentTime: values.paymentTime.format('YYYY-MM-DD'),
                subtotal: values.quantity * values.unitPrice * (1 + (values.rate || 0)) + (values.other_fee || 0)
            };
            setPurchaseData(updated);
            setIsEditing(false);
        });
    };

    return (
        <div className="purchase-request-page" style={{ padding: 24, background: '#fff', borderRadius: 8 }}>
            {/* 标题和编辑按钮 */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                <h2 style={{ margin: 0 }}>采购申请详情</h2>
                {isEditing ? (
                    <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
                        <Button type="primary" onClick={handleSave} style={{ marginRight: 10 }}>保存</Button>
                        <Button onClick={handleCancel}>取消</Button>
                    </div>
                ) : (
                    <Button type="primary" onClick={handleEdit}>编辑</Button>
                )}
            </div>

            <Form layout="vertical" form={form}>
                <Descriptions bordered column={2}>
                    <Descriptions.Item label="采购单号">
                        <Tag color="blue">{purchaseData.numbering}</Tag>
                    </Descriptions.Item>

                    <Descriptions.Item label="状态">
                        {isEditing ? (
                            <Form.Item name="status" noStyle>
                                <Select style={{ width: 120 }}>
                                    {Object.entries(statusMean).map(([k, v]) => (
                                        <Option key={k} value={Number(k)}>{v}</Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        ) : (
                            <Tag color={statusColor[purchaseData.status]}>
                                {statusMean[purchaseData.status]}
                            </Tag>
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="供应商">
                        {isEditing ? (
                            <Form.Item
                                label="供应商"
                                name="supplier"
                                rules={[
                                    { required: true, message: '请选择供应商' },
                                    {
                                        validator: (_, value) => {
                                            if (!value) return Promise.reject(new Error('请选择供应商'));
                                            const valStr = String(value);
                                            return valStr.startsWith('supplier-')
                                                ? Promise.resolve()
                                                : Promise.reject(new Error('请选择具体供应商（叶子节点），不可选择分类'));
                                        }
                                    }
                                ]}
                            >
                                <TreeSelect
                                    treeData={supplierTreeWithSuppliers}
                                    placeholder="请选择供应商（只能选择叶子节点）"
                                    allowClear
                                    treeDefaultExpandAll
                                />
                            </Form.Item>
                        ) : (
                            findSupplierName(purchaseData.supplier)
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="材料名称">
                        {isEditing ? (
                            <Form.Item name="name" noStyle>
                                <Input />
                            </Form.Item>
                        ) : (
                            purchaseData.name
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="规格型号">
                        {isEditing ? (
                            <Form.Item name="specification" noStyle>
                                <Input />
                            </Form.Item>
                        ) : (
                            <Tag>{purchaseData.specification}</Tag>
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="采购数量">
                        {isEditing ? (
                            <Form.Item name="quantity" noStyle>
                                <InputNumber min={0} />
                            </Form.Item>
                        ) : (
                            `${purchaseData.quantity} ${purchaseData.unit}`
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="单位">
                        {isEditing ? (
                            <Form.Item name="unit" noStyle>
                                <Input />
                            </Form.Item>
                        ) : (
                            purchaseData.unit
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="单价">
                        {isEditing ? (
                            <Form.Item name="unitPrice" noStyle>
                                <InputNumber min={0} />
                            </Form.Item>
                        ) : (
                            formatCurrency(purchaseData.unitPrice)
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="税率">
                        {isEditing ? (
                            <Form.Item name="rate" noStyle>
                                <InputNumber min={0} max={1} step={0.01} formatter={val => `${(val * 100).toFixed(0)}%`} parser={val => parseFloat(val) / 100} />
                            </Form.Item>
                        ) : (
                            `${(purchaseData.rate * 100).toFixed(0)}%`
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="其他费用">
                        {isEditing ? (
                            <Form.Item name="other_fee" noStyle>
                                <InputNumber min={0} />
                            </Form.Item>
                        ) : (
                            formatCurrency(purchaseData.other_fee)
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="小计" span={2}>
                        <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#cf1322' }}>
                            {formatCurrency(purchaseData.subtotal)}
                        </div>
                    </Descriptions.Item>

                    <Descriptions.Item label="采购日期">
                        <CalendarOutlined style={{ marginRight: 8 }} />
                        {isEditing ? (
                            <Form.Item name="purchaseTime" noStyle>
                                <DatePicker />
                            </Form.Item>
                        ) : (
                            purchaseData.purchaseTime
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="支付时间">
                        <CalendarOutlined style={{ marginRight: 8, color: '#52c41a' }} />
                        {isEditing ? (
                            <Form.Item name="paymentTime" noStyle>
                                <DatePicker />
                            </Form.Item>
                        ) : (
                            purchaseData.paymentTime
                        )}
                    </Descriptions.Item>

                    <Descriptions.Item label="备注信息" span={2}>
                        {isEditing ? (
                            <Form.Item name="remark" noStyle>
                                <Input.TextArea autoSize />
                            </Form.Item>
                        ) : (
                            <div style={{ color: '#fa8c16' }}>{purchaseData.remark}</div>
                        )}
                    </Descriptions.Item>
                </Descriptions>
            </Form>
        </div>
    );
};

export default PurchaseRequestPage;
